#!/bin/bash

# 服务配置
JAR_PATH="easymt.jar"
JAVA_BIN="/disk01/java/jdk17/bin/java"
PORT=8081
LOG_FILE="easymt.log"

# 函数：终止占用指定端口的进程
kill_port_process() {
  echo "正在检查端口 ${PORT} 的占用情况..."
  # 查找占用端口的PID（兼容不同系统）
  PID=$(lsof -ti :${PORT} || ss -tnlp | awk -v port=${PORT} '/:port / {split($6,pid,"[,=]"); print pid[2]}')

  if [ -n "${PID}" ]; then
    echo "发现占用端口 ${PORT} 的进程(PID: ${PID})，正在终止..."
    kill -9 ${PID} || { echo "终止进程失败！"; exit 1; }
    sleep 2  # 等待进程释放资源
    echo "进程终止完成。"
  else
    echo "端口 ${PORT} 未被占用。"
  fi
}

# 函数：启动服务
start_service() {
  echo "正在启动服务..."
  nohup ${JAVA_BIN} -jar ${JAR_PATH} >> ${LOG_FILE} 2>&1 &
  sleep 5  # 等待服务初始化

  # 检查是否启动成功
  if ps -p $! > /dev/null && (lsof -i :${PORT} | grep -q "LISTEN"); then
    echo "服务启动成功！PID: $!，日志文件: ${LOG_FILE}"
  else
    echo "服务启动失败，请检查日志: ${LOG_FILE}"
    exit 1
  fi
}

# 主流程
kill_port_process
start_service


